//分页组件
/**
 * pagetype:1 ,最多9个页码
 * pagetype:2 ,上一页，下一页
 * pagetype:3 ,包含上一页，下一页，首页，末页，每页多少条，跳转到多少页等.
 * pagetype:4 ,bshinfo style
 * @author zhf
 * @version 1.6
 * @email manbab@126.com
 */
(function ($) {
	$(document).on('click.data.api.href.#',"[href='#']",function(e){
 		e.preventDefault();
 	});
	
	$.widget( "custom.pager", {
		// default options
		options: {
			pagecount:null,//总页面
			pagesize:10,//每页条数
			pagetype:1,
			page:1,//当前页码
			url:"",
			toggle:null,
			form: null //"#aaa"
		},
		// the constructor 
		_create: function() {
			this.options = $.extend({}, this.options, this.element.data());
			
			//将页码绑定到控件
			this._on( $(this.options.form).find("[type='submit']"), {
				click : function(){
					  this._setOption("page","1");
				}
			});
			
			//做批量删除时的预处理
			this._on( $(this.options.form).find("[data-target=batchdelete]"), {
				click : function(event){
					  var $vals = $(":checked:not([data-type=checkbox])",this.options.toggle);
					  //makeArray将类数组对象转换为数组。
					  var values = $.makeArray($vals.map(function(){return $(this).val();}));
					  $(event.delegateTarget).data("pagervalue",values);
				}
			});
			
			//做选择单一项修改时的预处理
			this._on( $(this.options.form).find("[data-target=batchedit]"), {
				click : function(event){
					  var $vals = $(":checked:not([data-type=checkbox])",this.options.toggle);
					  //makeArray将类数组对象转换为数组。
					  if($vals.size()===0){
					  	 $(event.delegateTarget).data("pagervalue","");
					  }else if($vals.size()>1){
					     $(event.delegateTarget).data("pagervalue","manyvalues");
					  }else{
					     $(event.delegateTarget).data("pagervalue",$vals.val());
					  }
				}
			});
			
			//做批量ajax时的预处理
			this._on( $(this.options.form).find("[data-target=batchajax]"), {
				click : function(event){
					  var $vals = $(":checked:not([data-type=checkbox])",this.options.toggle);
					  //makeArray将类数组对象转换为数组。
					  var values = $.makeArray($vals.map(function(){return $(this).val();}));
					  $(event.delegateTarget).data("pagervalue",values);
				}
			});
			
			$(this.options.toggle).data("form",this.options.form);
			$(this.options.toggle).data("ele",this.element);
			$(this.options.form).data("toggle",this.options.toggle);
			
			//bind事件可以针对一个事件进行多次绑定，且不会被覆盖，on则会覆盖
			this._on( $(this.options.form), {
				submit  : function(){
					this._setOption("page","1");
					this.query();
					return false;
				},
				load : function(){
					var $tog = $(this.options.toggle);
					try{
						if($tog.innerHeight()>30){
							$tog.css("height",$tog.innerHeight());
						}
						$tog.html("").addClass("mask");
					}catch(e){}
					
					var params = $(this.options.form).serializeJson();
					params["page"] = this.options.page;
					//设置每页大小
					params["pageSize"] = this.options.pagesize;
						
					params["mat"] = Math.random();
					$tog.load(this.options.url,params,function(){
						//先做超长字符串截取
						$tog.find("[data-substring]").text(function(){
							try{
								var t = $(this).data("substring");
								if(parseInt(t)<$(this).text().length){
									$(this).attr("title",$(this).text());
									return $(this).text().substring(0,t)+"...";
								}
							}catch(e){}
						});
						//重绘分页
						$(this).data("ele").pager("reCreate");
						//移除loading图片
						$(this).css("height","auto").removeClass("mask");
					});
					return false;
				}
			});
			$(this.options.form).trigger("load");
		},
		
		reCreate: function( ) {
			var $table = $(this.options.toggle).children("[data-bsh-type='ajax']");
			this._setOption("page",$table.data("page"));
			this._setOption("pagecount",$table.data("pagecount"));
			this._creatHtml();
			this._bindHtml();
		},
		
		query: function( ) {
			$(this.options.form).trigger("load");
		},

		_creatHtml: function(  ) {
			this.element.html("");
			if(this.options.pagecount>1 || this.options.pagetype==3){
				this.element.append("<div class=\"pagination pagination-centered mypagination\"><ul class=\"pull-left\"></ul></div>");
				var page = this.options.page;
				var pagetype = this.options.pagetype;
				var pagesize = this.options.pagesize;
				var a = 1,b = 1;
				var pageCount = this.options.pagecount;
				if(pageCount){
				   a = page<=2?1:(page-2);
				   b = page<(pageCount-2)?(page<=2?(pageCount<=4?pageCount:4):(page+2)):pageCount;
				}
			
				var $ulhtml = this.element.find("ul");
				if(pagetype && pagetype===2){
					$ulhtml.append("<li class=\"disabled\" ><a href=\"#\">当前页码数："+page+";总页数："+pageCount+";</a></li>");
					if(page > 1){
						$ulhtml.append("<li data-page='"+(page-1)+"'><a href=\"#\"><i class=\"icon-backward\"></i>上一页</a></li>");
					}					
					if(page < pageCount){
						$ulhtml.append("<li data-page='"+(page+1)+"'><a href=\"#\">下一页<i class=\"icon-forward\"></i></a></li>");
					}
				}else if(pagetype && pagetype===3){
					if(page > 0){
						$ulhtml.append("<li data-page='1'><a href=\"#\" title=\"首页\"><i class=\"icon-step-backward\">首页</i></a></li>");
						$ulhtml.append("<li data-page='"+((page-1)<1?1:(page-1))+"'><a href=\"#\" title=\"上一页\"><i class=\"icon-backward\">上一页</i></a></li>");
					}
					for(var s=a;s<=b+2;s++){
						if(s<=pageCount)
						if(s===page){
							$ulhtml.append("<li class=\"active\" ><a href=\"#\">"+s+"</a></li>");
						}else{
							$ulhtml.append("<li data-page='"+s+"'><a href=\"#\">"+s+"</a></li>");
						}
					}
					if(page <= pageCount){
						$ulhtml.append("<li data-page='"+((page+1)>pageCount?pageCount:(page+1))+"'><a href=\"#\"  title=\"下一页\"><i class=\"icon-forward\">下一页</i></a></li>");
						$ulhtml.append("<li data-page='"+pageCount+"'><a href=\"#\" title=\"尾页\"><i class=\"icon-step-forward\">尾页</i></a></li>");
					}
					$ulhtml.append("<li class=\"disabled\" ><a href=\"#\">共:"+pageCount+"页</a></li>");
					$ulhtml.append("<li class=\"disabled\" ><a>每页:" +
							"<select name=\"pagesize\" class=\"pagesizeclass\"" +
							" style=\"width:42px;height:17px;margin:0px;padding:0px;font-size:12px;\" >" +
							"<option value='10' "+(pagesize==10?"selected":"")+">10</option>" +
							"<option value='20' "+(pagesize==20?"selected":"")+">20</option>" +
							"<option value='30' "+(pagesize==30?"selected":"")+">30</option>" +
							"<option value='50' "+(pagesize==50?"selected":"")+">50</option></select>条," +
							"跳转到:<input name=\"mypage\" class=\"mypageclass\" " +
							"style=\"width:22px;height:13px;margin:0px;padding:0px;font-size:12px;\"/>页" +
							"<button type=\"button\" class=\"btn1 btn-mini mypageclassbutton0 gobut\"" +
							" style=\"width:23px;height:20px;margin:0px;padding:0px;line-height:6px;font-size:12px;\" >go</button>" +
							"</a></li>");
				}else if(pagetype && pagetype===4){//bsh style
					$ulhtml.append("<li class='but' data-page='1'><a href=\"#\" title=\"首页\">首页</a></li>");
					if(page > 1){
						$ulhtml.append("<li class='but' data-page='"+(page-1)+"'><a href=\"#\" title=\"上一页\">上一页</a></li>");
					}
					for(var s=a;s<=b;s++){
						if(s===page){
							$ulhtml.append("<li class=\"active\" ><a href=\"#\">"+s+"</a></li>");
						}else{
							$ulhtml.append("<li data-page='"+s+"'><a href=\"#\">"+s+"</a></li>");
						}
					}
					if(page < pageCount){
						$ulhtml.append("<li class='but' data-page='"+(page+1)+"'><a href=\"#\"  title=\"下一页\">下一页</a></li>");
						
					}
					$ulhtml.append("<li class='but' data-page='"+pageCount+"'><a href=\"#\" title=\"尾页\">尾页</a></li>");
					$ulhtml.append("<li class=\"disabled\" ><a>" +
							"跳转到:<input name=\"mypage\" class=\"mypageclass\" " +
							"style=\"width:22px;height:13px;border:none;border-bottom:1px solid #ccc;margin:0px;padding:0px;font-size:12px;\"/>页" +
							"<label class=\"mypageclassbutton gobut\"" +
							" style=\"\" >确定</label>" +
							"</a></li>");
					$ulhtml.append("<li class=\"disabled\" ><a href=\"#\">共:"+pageCount+"页</a></li>");
				}else{
					if(page > 1){
						$ulhtml.append("<li data-page='"+(page-1)+"'><a href=\"#\"><i class=\"icon-backward\" ></i></a></li>");
					}
					for(var s=a;s<=b;s++){
						if(s===page){
							$ulhtml.append("<li class=\"active\" ><a href=\"#\">"+s+"</a></li>");
						}else{
							$ulhtml.append("<li data-page='"+s+"'><a href=\"#\">"+s+"</a></li>");
						}
					}
					if(page < pageCount){
						$ulhtml.append("<li data-page='"+(page+1)+"'><a href=\"#\"><i class=\"icon-forward\"></i></a></li>");
					}
					$ulhtml.append("<li class=\"disabled\" ><a href=\"#\">页码数："+page+"/"+pageCount+"</a></li>");
				}
			}else if(this.options.pagecount===1){
				this.element.html("<p class=\"text-error \" style=\"margin-top:10px;\">总页码：1页。</p>");
				
			}else if(this.options.pagecount<1){
				this.element.html("<p class=\"text-error \" style=\"margin-top:10px;margin-left:10px;\">抱歉，未查询到数据。。。</p>");
				
			}
		},
		
		_bindHtml: function() {
			this._on( this.element.find("li"), {
				click : function(event){
					var page = $(event.delegateTarget).data("page");
					if(page){
						//绑定变更的值到控件上
						this._setOption("page",page);
						//this._trigger("reLoad");
						this.query();
					}
				}
			});
			//绑定每页大小变更事件
			this._on(this.element.find(".pagesizeclass"),{
				change : function(event){
					var page = $(event.currentTarget).val();
					this._setOption("pagesize",page);
					this._setOption("page","1");
					this.query();
				}
			});
			//绑定填写页码进行跳转的事件
			this._on( this.element.find(".gobut"), {
				click : function(event){
					//绑定变更的值到控件上
					var val = this.element.find(".mypageclass").val();
					if(val&&val>0&&val<=this.options.pagecount){
						this._setOption("page",val);
						this.query();
					}else{
						alert("页码数越界！");
					}
				}
			});
		},
		
		// events bound via _on are removed automatically        
		// revert other modifications here
		destroy: function() {
			this.element.html("");
		},
		
		//_setOptions is called with a hash of all options that are changing         
		// always refresh when changing options     
		_setOptions: function() {
			// _super and _superApply handle keeping the right this-context      
			this._superApply( arguments );
		},
		
		_setOption: function( key, value ) {
			this.options[key] = value;
		}

	});	
})(jQuery);

(function($){
	//将表单转化成json组件
	//json方式可以解决ajax中文乱码问题		
	$.fn.serializeJson=function(){
		var serializeObj={};
		var array=this.serializeArray();
		var str=this.serialize();
		$(array).each(function(){
			if(serializeObj[this.name]){
				if($.isArray(serializeObj[this.name])){
					serializeObj[this.name].push(this.value);
				}else{
					serializeObj[this.name]=[serializeObj[this.name],this.value];
				}
			}else{
				serializeObj[this.name]=this.value;
			}
		});
		return serializeObj;
	};
 })(jQuery);

$(function() {
	$("[data-target='pager']").pager();
});
